#include <string>
#include <vector>
#include <cstring>
using namespace std;
/*
 * @lc app=leetcode.cn id=208 lang=cpp
 *
 * [208] 实现 Trie (前缀树)
 */

// @lc code=start
struct Node {
    string value;
    Node* children[26];
    Node(string _x): value(_x) { memset(children, NULL, sizeof children); }
    Node(): Node("") { }
};
class Trie {
public:

    Node *root;

    Trie() {
        root = new Node();
    }

    int c2i(char x) {
        return x - 'a';
    }
    
    void insert(string word) {
        Node *cur = root;
        for (int i = 0; i < word.size(); i++) {
            int index = c2i(word[i]);
            if (!cur->children[index]) {
                cur->children[index] = new Node();
            }
            cur = cur->children[index];
        }
        cur->value = word;
    }
    
    bool search(string word) {
        Node *cur = root;
        for (int i = 0; i < word.size(); i++) {
            if (!cur) return false;
            int index = c2i(word[i]);
            cur = cur->children[index];
        }
        return cur != NULL && cur->value == word;
    }
    
    bool startsWith(string prefix) {
        Node *cur = root;
        for (int i = 0; i < prefix.size(); i++) {
            if (!cur) return false;
            int index = c2i(prefix[i]);
            cur = cur->children[index];
        }
        return cur != NULL;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
// @lc code=end

